import Microi from '../config/microi.uniapp'
import type {
  ApiResponse,
  UserInfo,
  LoginParams,
  PageParams,
  ListResponse,
} from '../types'
import type { LoginParams as MicroiLoginParams } from '../config/microi.uniapp'

// 用户相关API - 兼容Microi系统
export const userApi = {
  // 用户登录 - 使用Microi系统
  login: (
    params: LoginParams
  ): Promise<ApiResponse<{ user: UserInfo | null; token: string }>> => {
    // 转换参数格式以兼容Microi
    const microiParams: MicroiLoginParams = {
      Account: params.username,
      Pwd: params.password,
      _CaptchaId: params._CaptchaId,
      _CaptchaValue: params._CaptchaValue,
    }

    return Microi.login(microiParams).then((response) => {
      if (response.Code === 1) {
        const userInfo = Microi.getCurrentUser()
        return {
          code: 200,
          success: true,
          data: {
            user: userInfo
              ? {
                  id: userInfo.id,
                  username: userInfo.username,
                  token: userInfo.token,
                  refreshToken: userInfo.refreshToken,
                }
              : null,
            token: userInfo?.token || '',
          },
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: { user: null, token: '' },
          message: response.Msg || '登录失败',
        }
      }
    })
  },

  // 用户注册 - 使用Microi系统
  register: (
    params: LoginParams
  ): Promise<ApiResponse<{ user: UserInfo | null; token: string }>> => {
    // 注册接口需要根据实际后端API调整
    return Microi.Post('/api/SysUser/register', {
      Account: params.username,
      Pwd: params.password,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: {
            user: response.Data,
            token: response.Data?.token || '',
          },
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: { user: null, token: '' },
          message: response.Msg || '注册失败',
        }
      }
    })
  },

  // 获取用户信息 - 使用Microi系统
  getUserInfo: (): Promise<ApiResponse<UserInfo | null>> => {
    return Microi.Post('/api/SysUser/getCurrentUser', {
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '获取用户信息失败',
        }
      }
    })
  },

  // 更新用户信息
  updateUserInfo: (
    data: Partial<UserInfo>
  ): Promise<ApiResponse<UserInfo | null>> => {
    return Microi.Post('/api/SysUser/updateUserInfo', {
      ...data,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '更新用户信息失败',
        }
      }
    })
  },

  // 修改密码
  changePassword: (data: {
    oldPassword: string
    newPassword: string
  }): Promise<ApiResponse<null>> => {
    return Microi.Post('/api/SysUser/changePassword', {
      OldPassword: data.oldPassword,
      NewPassword: data.newPassword,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: null,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '修改密码失败',
        }
      }
    })
  },

  // 用户登出 - 使用Microi系统
  logout: (): Promise<ApiResponse<null>> => {
    return new Promise((resolve) => {
      Microi.logout()
      resolve({
        code: 200,
        success: true,
        data: null,
        message: '登出成功',
      })
    })
  },

  // 刷新token - 使用Microi系统
  refreshToken: (): Promise<
    ApiResponse<{ token: string; refreshToken: string }>
  > => {
    return Microi.refreshToken().then((success) => {
      if (success) {
        const token = Microi.getToken()
        const userInfo = Microi.getCurrentUser()
        return {
          code: 200,
          success: true,
          data: {
            token: token || '',
            refreshToken: userInfo?.refreshToken || '',
          },
          message: 'Token刷新成功',
        }
      } else {
        return {
          code: 500,
          success: false,
          data: { token: '', refreshToken: '' },
          message: 'Token刷新失败',
        }
      }
    })
  },
}

// 通用API - 兼容Microi系统
export const commonApi = {
  // 上传文件
  uploadFile: (
    filePath: string,
    name = 'file'
  ): Promise<ApiResponse<{ url: string }>> => {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${Microi.getApiBase()}/api/Common/uploadFile`,
        filePath,
        name,
        header: {
          authorization: `Bearer ${Microi.getToken()}`,
          osclient: Microi.getOsClient(),
          clienttype: Microi.getClientType(),
          clientsystem: Microi.getClientSystem(),
        },
        success: (res: any) => {
          try {
            const data = JSON.parse(res.data)
            if (data.Code === 1) {
              resolve({
                code: 200,
                success: true,
                data: { url: data.Data },
                message: data.Msg,
              })
            } else {
              reject({
                code: data.Code,
                success: false,
                data: null,
                message: data.Msg || '上传失败',
              })
            }
          } catch (error: any) {
            reject({
              code: 500,
              success: false,
              data: null,
              message: '解析响应失败',
            })
          }
        },
        fail: (error: any) => {
          reject({
            code: 500,
            success: false,
            data: null,
            message: error.errMsg || '上传失败',
          })
        },
      })
    })
  },

  // 获取配置信息 - 使用Microi系统
  getConfig: (): Promise<ApiResponse<Record<string, any> | null>> => {
    return Microi.getSysConfig().then((config) => {
      return {
        code: 200,
        success: true,
        data: config,
        message: '获取配置成功',
      }
    })
  },

  // 获取字典数据
  getDict: (type: string): Promise<ApiResponse<Record<string, any> | null>> => {
    return Microi.Post('/api/Common/getDict', {
      Type: type,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '获取字典数据失败',
        }
      }
    })
  },

  // 获取验证码 - 使用Microi系统
  getCaptcha: (): Promise<
    ApiResponse<{ captchaSrc: string; captchaId: string } | null>
  > => {
    return Microi.getCaptcha().then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: {
            captchaSrc: response.CaptchaSrc,
            captchaId: response.CaptchaId,
          },
          message: '获取验证码成功',
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: '获取验证码失败',
        }
      }
    })
  },

  // 获取服务器时间
  getServerTime: (): Promise<ApiResponse<string | null>> => {
    return Microi.getDateTimeNow().then((time) => {
      return {
        code: 200,
        success: true,
        data: time,
        message: '获取服务器时间成功',
      }
    })
  },
}

// 示例业务API - 兼容Microi系统
export const exampleApi = {
  // 获取列表数据
  getList: (
    params: PageParams & { keyword?: string }
  ): Promise<ApiResponse<ListResponse<any> | null>> => {
    return Microi.Post('/api/Example/getList', {
      ...params,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '获取列表失败',
        }
      }
    })
  },

  // 获取详情
  getDetail: (id: string | number): Promise<ApiResponse<any | null>> => {
    return Microi.Post('/api/Example/getDetail', {
      Id: id,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '获取详情失败',
        }
      }
    })
  },

  // 创建
  create: (data: any): Promise<ApiResponse<any | null>> => {
    return Microi.Post('/api/Example/create', {
      ...data,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '创建失败',
        }
      }
    })
  },

  // 更新
  update: (
    id: string | number,
    data: any
  ): Promise<ApiResponse<any | null>> => {
    return Microi.Post('/api/Example/update', {
      Id: id,
      ...data,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: response.Data,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '更新失败',
        }
      }
    })
  },

  // 删除
  delete: (id: string | number): Promise<ApiResponse<null>> => {
    return Microi.Post('/api/Example/delete', {
      Id: id,
      OsClient: Microi.getOsClient(),
    }).then((response) => {
      if (response.Code === 1) {
        return {
          code: 200,
          success: true,
          data: null,
          message: response.Msg,
        }
      } else {
        return {
          code: response.Code,
          success: false,
          data: null,
          message: response.Msg || '删除失败',
        }
      }
    })
  },
}

// 导出所有API
export default {
  user: userApi,
  common: commonApi,
  example: exampleApi,
}
